package com.roc.web.action.terminal;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.TermInfoDownLoad;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@SuppressWarnings("serial")
@Component
@Scope("prototype")
@Namespace("/terminalDownload")
public class TerminalDownLoadAction extends PaginationBaseAction{
	private TerminalDownLoadSearchCondition searchCondition;
	private Logger logger=LogManager.getLogger(TerminalDownLoadAction.class);
	private InputStream file;
	
	@Autowired
	private IPageService pagenitionService;
	/**
	 * 初始化下载页面
	 * @return
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/terminal/terminal_download.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String init(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())){
			searchCondition=new TerminalDownLoadSearchCondition();
			searchCondition.setStart(Constance.obtainYesterday());
			searchCondition.setEnd(Constance.currTime());
			logger.info("初始化下载页面");
			return SUCCESS;
		}
		addActionMessage("无权限访问");
		return ERROR;
	}
	
	
	@Action(value="termList",results={@Result(name="success",location="/pages/terminal/terminal_download.jsp")})
	public String queryTermInfoDownLoadList(){
		try {
			Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
					|| op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())){
				if(searchCondition == null){
					searchCondition = (TerminalDownLoadSearchCondition) getSearchConditionFromSession();
					if(searchCondition == null){
						searchCondition = new TerminalDownLoadSearchCondition();
					}
				}
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}
				dealWithTheListSpecially(searchRsList);
				addActionMessage("当前条件下统计到【"+rows+"】条记录");
				getRequest().setAttribute("searchRsList", searchRsList);
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(searchCondition);
				return SUCCESS;
			}
			addActionMessage("无权限访问");
			return ERROR;
		}catch(Exception e){
			logger.error("终端信息查询异常",e);
			addActionError("终端信息查询异常");
			return ERROR;
		}
	}
	
	@Override
	protected void dealWithTheListSpecially(List<Object> list) {
		if(list.size()>0){
			List<Object> newList=new ArrayList<Object>();
			for(int i=0;i<list.size();i++){	
				Object[] obj=(Object[]) list.get(i);
				TermInfoDownLoad info=new TermInfoDownLoad();
				info.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				info.setTermId(Constance.Null2EmptyTrim(obj[1]));
				info.setDeviceCd(Constance.Null2EmptyTrim(obj[2]));
				info.setBrand(Constance.Null2EmptyTrim(obj[3]));
				info.setType(Constance.Null2EmptyTrim(obj[4]));
				info.setModel(Constance.Null2EmptyTrim(obj[5]));
				info.setDate(Constance.Null2EmptyTrim(obj[6]));
				newList.add(info);
			}
			list.clear();
			list.addAll(newList);
		}
	}


	@Action(value = "download", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "text/plain", "inputName",
					"file", "contentDisposition",
					"attachment;filename=${excelName}.txt", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp")})
	public String exportTerminalInfo() throws Exception{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())){			
			if(searchCondition == null){
				searchCondition = (TerminalDownLoadSearchCondition) getSearchConditionFromSession();
				if(searchCondition == null){
					searchCondition = new TerminalDownLoadSearchCondition();
				}
			}
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()),rows);
			}
			dealWithTheListToTXT(searchRsList,searchCondition.getFlag());
			return SUCCESS;
		}
		addActionMessage("无权限访问");
		return ERROR;
	}
	

	protected void dealWithTheListToTXT(List<Object> list,String flag) {
		try {
			ByteArrayOutputStream out=new ByteArrayOutputStream();
			if(list.size()>0){
				if("downloadAdded".equals(flag)){
					for(int i=0;i<list.size();i++){
						Object[] obj=(Object[]) list.get(i);
						StringBuffer sb=new StringBuffer();
						sb.append("I,");
						sb.append(Constance.Null2EmptyTrim(obj[0])+",0848500000,1,");
						sb.append(Constance.Null2EmptyTrim(obj[1])+",00,110000000000000000000000000000,,");
						sb.append(Constance.Null2EmptyTrim(obj[7])+",,,,");
						sb.append("084850"+Constance.Null2EmptyTrim(obj[0]).substring(3,7)+",");
						sb.append(Constance.Null2EmptyTrim(obj[2])+",");
						sb.append(Constance.Null2EmptyTrim(obj[3])+",");
						sb.append(Constance.Null2EmptyTrim(obj[5])+",");
						sb.append(Constance.Null2EmptyTrim(obj[6])+",,1,1,1,1,1,消费\r\n");
						out.write(sb.toString().getBytes());
						}
				}else if("downloadStock".equals(flag)){
					for(int i=0;i<list.size();i++){
						Object[] obj=(Object[]) list.get(i);
						StringBuffer sb=new StringBuffer();
						sb.append(Constance.Null2EmptyTrim(obj[0])+",");
						sb.append(Constance.Null2EmptyTrim(obj[1])+",0848500000,084850"+Constance.Null2EmptyTrim(obj[0]).substring(3,7)+",");
						sb.append(Constance.Null2EmptyTrim(obj[2])+",");
						sb.append(Constance.Null2EmptyTrim(obj[3])+",");
						sb.append(Constance.Null2EmptyTrim(obj[5])+",");
						sb.append(Constance.Null2EmptyTrim(obj[6])+",");
						sb.append(Constance.Null2EmptyTrim(obj[4])+",1,1,1,1,0,消费\r\n");
						out.write(sb.toString().getBytes());
						}
				}
			  }
			byte[] ba = out.toByteArray();
			file = new ByteArrayInputStream(ba);
			out.flush();
			out.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				addActionError(e.getMessage());
			}
	}


	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {		
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_TERM_INFO_DOWN_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (TerminalDownLoadSearchCondition) getSession().getAttribute(SEARCH_SESSION_TERM_INFO_DOWN_QUERY);
	}

	@Override
	protected String getInitPageSize() {		
		return Constance.PAGE_MAX_SIZE+"";
	}


	

	public InputStream getFile() {
		return file;
	}


	public void setFile(InputStream file) {
		this.file = file;
	}


	public TerminalDownLoadSearchCondition getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(TerminalDownLoadSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}


	public String getExcelName() {
		String prefix="";
		if("downloadStock".equals(searchCondition.getFlag())){
			prefix="存量终端信息";
		}else if("downloadAdded".equals(searchCondition.getFlag())){
			prefix="新增终端信息";
		}
		String excelName ="term_"+prefix+ Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成终端信息名称失败了！");
		}
		return excelName;
	}
}
